package com.ljh.gateway.filter;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.ljh.common.pojo.Result;
import com.ljh.common.utils.JWTUtils;
import com.ljh.gateway.properties.AuthWhiteList;
import io.jsonwebtoken.Claims;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.util.Set;

/**
 * @author: Themberfue
 * @date: 2025/4/23 19:13
 * @description:
 */
@Slf4j
@Component
public class AuthFilter implements GlobalFilter, Ordered {
//    private static final Set<String> whiteList = Set.of(
//            "/user/login",
//            "/user/register");

    @Autowired
    ObjectMapper objectMapper;

    // ? 放行白名单
    @Autowired
    AuthWhiteList authWhiteList;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();

        // TODO 1. 校验路径是否在白名单里
        String path = request.getURI().getPath();
        if (match(path, authWhiteList.getUrl())) {
            return chain.filter(exchange);
        }

        // TODO 2. 校验 token
        // TODO 2.1 从 header中获取 token
        String userToken = request.getHeaders().getFirst("user_token");
        log.info("从header中获取token: {}", userToken);

        if (!StringUtils.hasLength(userToken)) {
            return unauthorizedResponse(exchange, "令牌不能为空!");
        }

        // TODO 2.2 验证用户 token
        Claims claims = JWTUtils.parseJWT(userToken);
        if (null == claims){
            log.info("令牌验证失败");
            return unauthorizedResponse(exchange, "令牌过期或者不合法!");
        }

        return chain.filter(exchange);
    }

    private boolean match(String path, Set<String> whiteList) {
        if (null == whiteList || whiteList.isEmpty()) {
            return false;
        }
        return whiteList.contains(path);
    }

    @SneakyThrows
    private Mono<Void> unauthorizedResponse(ServerWebExchange exchange, String errMsg) {
        // TODO 1. 设置响应状态码和响应头
        ServerHttpResponse response = exchange.getResponse();
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        response.getHeaders()
                .add(HttpHeaders.CONTENT_TYPE, MediaType.APPLICATION_JSON_VALUE);

        // TODO 2. 构造返回
        Result result = Result.fail(errMsg);
        DataBuffer dataBuffer = response.bufferFactory()
                        .wrap(objectMapper.writeValueAsBytes(result));

        return response.writeWith(Mono.just(dataBuffer));
    }

    @Override
    public int getOrder() {
        return Ordered.LOWEST_PRECEDENCE; // ? 数字越低，优先级越高
    }
}
